package com.mf.morefun.ui.person_detail;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.apkfuns.logutils.LogUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.mf.morefun.R;
import com.mf.morefun.base.BaseBusActivity;
import com.mf.morefun.bean.ResultBean;
import com.mf.morefun.bean.UserInfoBean;
import com.mf.morefun.constant.Configuration;
import com.mf.morefun.listener.MyRequestListener;
import com.mf.morefun.requestbean.RequestUserBean;
import com.mf.morefun.ui.myclass.fragment.HomeWorkFragment;
import com.mf.morefun.ui.person_detail.fragment.PersonInfoFragment;
import com.mf.morefun.util.TransformationUtils;
import com.mf.morefun.widget.NetErrorPop;
import com.zhcx.zhcxlibrary.utils.DeviceUtils;
import com.zhcx.zhcxlibrary.utils.StringUtils;
import com.zhcx.zhcxlibrary.utils.ToastUtils;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import butterknife.BindView;

public class PersonDetailActivity extends BaseBusActivity {
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_head)
    ImageView ivHead;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_star)
    TextView tvStar;
    @BindView(R.id.tv_flower)
    TextView tvFlower;
    @BindView(R.id.tv_trophy)
    TextView tvTrophy;
    @BindView(R.id.iv_info)
    ImageView ivInfo;
    @BindView(R.id.tv_info)
    TextView tvInfo;
    @BindView(R.id.ll_info)
    LinearLayout llInfo;
    @BindView(R.id.iv_works)
    ImageView ivWorks;
    @BindView(R.id.tv_works)
    TextView tvWorks;
    @BindView(R.id.ll_works)
    LinearLayout llWorks;
    @BindView(R.id.fl_content)
    FrameLayout flContent;
    private PersonInfoFragment mPersonInfoFragment;//作品
    private HomeWorkFragment mHomeWorkFragment;//成就
    private FragmentManager fManager;
    @Override
    protected int getNaviteColor() {
        return 0;
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_persondetail;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        llInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectItem(0);
                changeButtonColor(0);
            }
        });
        llWorks.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectItem(1);
                changeButtonColor(1);
            }
        });
        fManager = getSupportFragmentManager();
        showCicleImg();
        tvStar.setText(getIntent().getStringExtra("Stars"));
        tvFlower.setText(getIntent().getStringExtra("Flows"));
        tvTrophy.setText(getIntent().getStringExtra("EnergyStones"));
        selectItem(0);
        changeButtonColor(0);
        if (getIntent().getStringExtra("UserType").equals("1")){
            tvInfo.setText("学员信息");
            llWorks.setVisibility(View.VISIBLE);
        }else if(getIntent().getStringExtra("UserType").equals("2")){
            tvInfo.setText("老师信息");
            llWorks.setVisibility(View.GONE);
        }else {
            tvInfo.setText("管理员信息");
            llWorks.setVisibility(View.GONE);
        }
    }
    private void showCicleImg() {
        CircleCrop circleCrop = new CircleCrop();
        RequestOptions options = RequestOptions.bitmapTransform(circleCrop);
        Glide.with(PersonDetailActivity.this).asBitmap().load(getIntent().getStringExtra("HeadPortrait")).listener(new MyRequestListener(ivHead, PersonDetailActivity.this, DeviceUtils.dip2px(PersonDetailActivity.this, 30), DeviceUtils.dip2px(PersonDetailActivity.this, 30))).apply(options).into(new TransformationUtils(ivHead, PersonDetailActivity.this, DeviceUtils.dip2px(PersonDetailActivity.this, 30), DeviceUtils.dip2px(PersonDetailActivity.this, 30)));
    }
    @Override
    protected void initData() {
        initGetUser(getIntent().getStringExtra("userId"));
    }

    private void initGetUser(String userId) {
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.USERINFO);
        RequestUserBean userBean = new RequestUserBean();
        userBean.setId(userId);
        params.setBodyContent(JSON.toJSONString(userBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                LogUtils.d(result);
                if (!StringUtils.isEmpty(result)){
                    ResultBean mResult = JSON.parseObject(result, ResultBean.class);
                    if (mResult.getErrorCode() == 0){
                        if (!StringUtils.isEmpty(mResult.getResult())){
                            UserInfoBean user = JSON.parseObject(mResult.getResult(), UserInfoBean.class);
                            if (null != user.getUserFinance()){
                                tvStar.setText(user.getUserFinance().getStars() + "");
                                tvFlower.setText(user.getUserFinance().getFlows() + "");
                                tvTrophy.setText(user.getUserFinance().getEnergyStones() + "");
                            }
                        }
                    }else {
                        ToastUtils.show(getApplicationContext(), mResult.getMessage(), 100);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mHandler.sendEmptyMessage(101);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 101:
                    NetErrorPop errorPop = new NetErrorPop(PersonDetailActivity.this);
                    errorPop.showPop("");
                    break;
            }
        }
    };
    private void changeButtonColor(int index) {
        switch (index) {
            case 1:
                ivWorks.setImageResource(R.mipmap.mine_yes_works_icon);
                tvWorks.setTextColor(getResources().getColor(R.color.white));
                llWorks.setBackgroundResource(R.mipmap.mineselected);
                ivInfo.setImageResource(R.mipmap.persondetailuser);
                tvInfo.setTextColor(0xff999999);
                llInfo.setBackgroundResource(R.mipmap.noselect);
                break;
            case 0:
                ivWorks.setImageResource(R.mipmap.mine_not_works_icon);
                tvWorks.setTextColor(0xff999999);
                llWorks.setBackgroundResource(R.mipmap.noselect);
                ivInfo.setImageResource(R.mipmap.persondetailusered);
                tvInfo.setTextColor(getResources().getColor(R.color.white));
                llInfo.setBackgroundResource(R.mipmap.mineselected);
                break;
        }
    }

    //切换fragment的方法
    private int mIndex = -1;

    private void selectItem(int index) {
        FragmentTransaction transaction = fManager.beginTransaction();
        hideFragments(transaction);
        switch (index) {
            case 0:
                if (mIndex == 0) {
                    return;
                }
                mIndex = 0;
                if (mPersonInfoFragment == null) {
                    mPersonInfoFragment = PersonInfoFragment.newInstance(getIntent().getStringExtra("HeadPortrait"),
                            getIntent().getStringExtra("Name"),
                            getIntent().getStringExtra("Phone"),
                            getIntent().getStringExtra("Password"),
                            getIntent().getStringExtra("Birthday"),
                            getIntent().getStringExtra("City"),
                            getIntent().getStringExtra("userId"),
                            getIntent().getStringExtra("EnableEnd"),
                            getIntent().getStringExtra("Address"),
                            getIntent().getStringExtra("UserType"));
                    transaction.add(R.id.fl_content, mPersonInfoFragment);
                } else {
                    transaction.show(mPersonInfoFragment);
                }
                break;
            case 1:
                if (mIndex == 1) {
                    return;
                }
                mIndex = 1;
                if (mHomeWorkFragment == null) {
                    mHomeWorkFragment = mHomeWorkFragment = HomeWorkFragment.newInstance(getIntent().getStringExtra("userId"), getIntent().getStringExtra("type"), getIntent().getStringExtra("CLASSID"), getIntent().getStringExtra("UserType"));
                    transaction.add(R.id.fl_content, mHomeWorkFragment);
                } else {
                    transaction.show(mHomeWorkFragment);
                }
                break;
        }
        transaction.commitAllowingStateLoss();
    }

    private void hideFragments(FragmentTransaction transaction) {
        if (mPersonInfoFragment != null) {
            transaction.hide(mPersonInfoFragment);
        }
        if (mHomeWorkFragment != null) {
            transaction.hide(mHomeWorkFragment);
        }
    }


}
